package Task17;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

import org.apache.log4j.Logger;

public class Controller {
	public static final Logger Log=Logger.getLogger(Controller.class);
	
	private boolean happendError=true;
	public Model myModel=new Model();
	public String workDir="c:\\";
	
	//bug in move with case: create a new dir. Don't delete old file.
	public String prompt() {
		String sResult="";
		File f=new File(workDir);
		if(!f.exists()) {sResult="Prompt:"+workDir+"Not found directory."; Log.error(sResult);}
		else{
		        if(f.isDirectory()){
		                System.out.print(workDir+">");
		                Scanner inp=new Scanner(System.in);
		                String command;
		                command=inp.nextLine();
		                Log.info("[workDir is: "+workDir+"] Input command: "+command);
		                
		                sResult+=tryRun(command);
		                
		                
		        }
		        else{ sResult="Error. It is not directory "+f.toString();  
		        Log.error(sResult);
		        }
		}
		return sResult;
	}
	
	private String tryRun(String command){
		String sResult="";
		Scanner inp=new Scanner(System.in);
		
		 try{
         	sResult=execute(parser(command));
         	//if(happendError) happendError=true; else happendError=false; 
         }
         catch(NullPointerException e){
 			sResult="No command";
 			happendError=true;
         }
         catch(FileNotFoundException ex){
         	
         	String sFileFrom=myModel.arg1;
       	  	String sFileTo=myModel.arg2;
       	  	String message=ex.getMessage() + " in the specified directory. Do you want to create a new directory? (y/n)";
                   System.out.println(message);
                   Log.info(message);
                   if(inp.nextLine().toString().equals("y")){
                	   Log.info("User's answer: Yes.");
                           File fileTo=new File(sFileTo);
                           File newDir=new File(fileTo.getParent());
                           
                           if(newDir.mkdirs()) {  //Created directory
                         	  myModel.arg1=sFileFrom; //Try made copy method
                         	  myModel.arg2=sFileTo;
                         	  myModel.numArg=1;
                         	  myModel.workDir=workDir;
                         	  try {
                         		 
                         		File newFile=new File(myModel.arg2);	//Get name of file without absolute path
        		              	  	String myCommand="copy "+myModel.arg1+" "+newFile.getName();
        		              	  	String workDirCopy=workDir;  //for create arg2 in absolute path
        		              	  	workDir=newFile.getParent();  
            		              	  	
        		              	  	sResult=execute(parser(myCommand));	//copy
        		              	  	workDir=workDirCopy; 
                            		
        		              	if(command.startsWith("move")){	//if command==move
  		              	  		myCommand="del "+myModel.arg1;
  		              	  		sResult=execute(parser(myCommand));	//del	//bug in deleting one file. File not deleting. !!!
  		              	  		happendError=false;
                         	} 	
                               	
								} catch (FileNotFoundException e) {sResult="Error. File not found. Sorry.";
								} catch (NullPointerException e) {sResult="Error. Null pointerException. Sorry.";
								} catch (FileAlreadyExistException e) {sResult="Error. File already exist. Sorry.";
								} catch (IOException e) {sResult="Error. IOException. Sorry.";
								} catch (DirectoryIsRootException e) {sResult=workDir+" is root! Impossible command.";
								} catch (MyFileNotFoundException e) {sResult="Error. File not found. Sorry.";}
                         }
                   }
                   else {Log.info("User's answer: No."); sResult="Operation canceled.";}
         }
         catch(IOException e){
         	sResult="Error. IOException.";
         } catch (FileAlreadyExistException e) {
        	 String message="File exists. \nRewrite? (y/n)";
         	 System.out.println(message);
         	 Log.info("File exists. Rewrite? (y/n)");
                      if(inp.nextLine().toString().equals("y")){
                    	  Log.info("User's answer: Yes.");
                    	  try {
                     	String arg1copy=myModel.arg1;
                     	String arg2copy=myModel.arg2;
                     	
                     	String myCommand="del "+myModel.arg2;
		              	  	sResult=execute(parser(myCommand));	//del
                     	
		              	  	File newFile=new File(arg2copy);	//Get name of file without absolute path
		              	  	myCommand="copy "+arg1copy+" "+newFile.getName();
		              	  	sResult=execute(parser(myCommand));	//copy
                  		
		              	  	if(command.startsWith("move")){	//if command==move
		              	  		myCommand="del "+myModel.arg1;
		              	  		sResult=execute(parser(myCommand));	//del
		              	  		happendError=false;
                     	}
		              	  	
                     	} catch (FileNotFoundException e1) {sResult="Error. File not found. Sorry.";
							} catch (NullPointerException e1) {sResult="Error. Null pointerException. Sorry.";
							} catch (FileAlreadyExistException e1) {sResult="Error. File already exist. Sorry.";
							} catch (IOException e1) {sResult="Error. IOException. Sorry.";
							} catch (DirectoryIsRootException e1) {sResult=workDir+" is root! Impossible command."; 
							} catch (MyFileNotFoundException e1) {sResult="Error. File not found. Sorry.";}
                     }
                     else {Log.info("User's answer: No."); sResult="Operation canceled.";}
			} catch (DirectoryIsRootException e) {sResult=workDir+" is root! Impossible command.";
			} catch (MyFileNotFoundException e)  {sResult="Not found directory";}
		
		 if(happendError) Log.error(sResult+ " [workDir is: "+workDir+"]"); else Log.info("Operation complete."); 
		 return sResult;
	} 
		
private CommandInterface parser(String command) throws NullPointerException{   
        
        String[] arrayCommand=command.split(" ");
        
        //Define myModel
        myModel.numArg=arrayCommand.length-1;
        if(myModel.numArg>0) myModel.arg1=arrayCommand[1];
        if(myModel.numArg>1) myModel.arg2=arrayCommand[2];
        myModel.workDir=workDir;
        
        //Get instance of command
        String sCommand=arrayCommand[0];
        CommandInterface myCommand=myModel.getObjectCommand(sCommand);
    	
        return myCommand;
}

private String execute(CommandInterface myCommand) throws FileNotFoundException, FileAlreadyExistException, IOException, DirectoryIsRootException, MyFileNotFoundException{
	String sResultMethod;
	String sError=myCommand.getError(); // Check for errors and change happendError flag!
	if(myCommand.happendError) {sResultMethod=sError; happendError=true;} else {sResultMethod=myCommand.getResult();happendError=false;}
	workDir=myModel.workDir;
	return sResultMethod;
}

public static class FileAlreadyExistException extends Exception {}
public static class DirectoryIsRootException extends Exception {}
public static class MyFileNotFoundException extends Exception {}

}
